package com.ymdx.service.impl;

import com.ymdx.entity.IdEntity;
import com.ymdx.service.BaseService;
import com.ymdx.util.Page;
//import org.hibernate.Criteria;
//import org.hibernate.HibernateException;
//import org.hibernate.Session;
//import org.hibernate.query.Query;
//import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * service层基类
 * Created by yangliwei on 2017/8/13.
 */
public abstract class BaseServiceImpl<T extends IdEntity, PK extends Serializable> implements
        BaseService<T, PK> {
    @Resource
    protected HibernateTemplate hibernateTemplate;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public void save(T entity) {
        // TODO Auto-generated method stub
        if (entity instanceof IdEntity) {
            if (entity.getId() != null) {
                entity.setModifyTime(new Date());
            }
        }
        hibernateTemplate.saveOrUpdate(entity);
    }

    @Override
    public T getById(Class<T> clazz, PK id) {
        // TODO Auto-generated method stub
        T result = hibernateTemplate.get(clazz, id);
        if (result != null && result.getValid() == true)
            return result;
        else return null;
    }


    //不支持主键的查询
    public List<T> getByExample(T entity) {
        if (entity instanceof IdEntity) {
            //因为ModifyTime 新建对象自动生成，这里需要去掉
            entity.setModifyTime(null);
            entity.setValid(true);
        }
        return hibernateTemplate.findByExample(entity);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public void delete(T entity) {
        if (entity instanceof IdEntity) {
            ((IdEntity) entity).setValid(false);
            ((IdEntity) entity).setDeleteTime(new Date());
            hibernateTemplate.saveOrUpdate(entity);
        } else {
            try {
                hibernateTemplate.delete(entity);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}
